<?php

class Project_category_model extends MY_Model {

    public function __construct() {
	parent::__construct();
	$this->table = 'alsa_project_category';
    }

    public function max_order() {
	$sql = "select IFNULL(max(`order`),0) as max_order from {$this->table};";

	$query = $this->db->query($sql);

	return $query->row()->max_order;
    }

    public function order($id, $new_order) {
	$row = $this->find($id);

	if ($row->order > $new_order) {
	    $end_order = $row->order - 1;
	    $sql = "update `{$this->table}`
            set `order`=`order`+1
            where `order`>={$new_order}
            and `order`<={$end_order};";
	} else {
	    $start_order = $row->order + 1;
	    $sql = "update `{$this->table}`
            set `order`=`order`-1
            where `order`>={$start_order}
            and `order`<={$new_order};";
	}

	$this->db->query($sql);

	return $this->update($id, array('order' => $new_order));
    }

}
